import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import type { RouteMeta as CustomRouteMeta } from '@/types'

// 扩展路由元信息类型
declare module 'vue-router' {
  interface RouteMeta extends CustomRouteMeta {}
}

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        // --- 前台路由 ---
        {
            path: '/',
            name: 'Home',
            component: () => import('@/views/HomeView.vue'),
            meta: {
                title: '首页',
                icon: 'HomeFilled',
            },
        },
        {
            path: '/products',
            name: 'Products',
            component: () => import('@/views/product/ProductList.vue'),
            meta: {
                title: '商品列表',
                icon: 'Goods',
            },
        },
        {
            path: '/product/:id',
            name: 'ProductDetail',
            component: () => import('@/views/product/ProductDetail.vue'),
            meta: {
                title: '商品详情',
            },
        },
        {
            path: '/cart',
            name: 'Cart',
            component: () => import('@/views/CartView.vue'),
            meta: {
                title: '购物车',
                icon: 'ShoppingCart',
                requiresAuth: true,
            },
        },
        {
            path: '/orders',
            name: 'Orders',
            component: () => import('@/views/order/OrderList.vue'),
            meta: {
                title: '我的订单',
                icon: 'Document',
                requiresAuth: true,
            },
        },
        {
            path: '/profile',
            name: 'Profile',
            component: () => import('@/views/user/ProfileView.vue'),
            meta: {
                title: '个人中心',
                icon: 'User',
                requiresAuth: true,
            },
        },
        {
            path: '/addresses',
            name: 'Addresses',
            component: () => import('@/views/user/AddressList.vue'),
            meta: {
                title: '收货地址',
                icon: 'Location',
                requiresAuth: true,
            },
        },
        {
            path: '/points',
            name: 'Points',
            component: () => import('@/views/user/PointsView.vue'),
            meta: {
                title: '积分中心',
                icon: 'Star',
                requiresAuth: true,
            },
        },
        {
            path: '/login',
            name: 'Login',
            component: () => import('@/views/auth/LoginView.vue'),
            meta: {
                title: '登录',
                requiresGuest: true,
            },
        },
        {
            path: '/register',
            name: 'Register',
            component: () => import('@/views/auth/RegisterView.vue'),
            meta: {
                title: '注册',
                requiresGuest: true,
            },
        },
        {
            path: '/about',
            name: 'About',
            component: () => import('@/views/AboutView.vue'),
            meta: {
                title: '关于我们',
                icon: 'InfoFilled',
            },
        },
        {
            path: '/search',
            name: 'Search',
            component: () => import('@/views/SearchView.vue'),
            meta: {
                title: '搜索结果',
            },
        },

        // --- 后台路由 ---
        {
            path: '/admin',
            component: () => import('@/components/layout/AdminLayout.vue'),
            meta: { requiresAdmin: true },
            children: [
                {
                    path: '',
                    redirect: '/admin/dashboard',
                },
                {
                    path: 'dashboard',
                    name: 'AdminDashboard',
                    component: () => import('@/views/admin/DashboardView.vue'),
                    meta: { title: '主面板' },
                },
                {
                    path: 'products',
                    name: 'AdminProducts',
                    component: () => import('@/views/admin/product/ProductListView.vue'),
                    meta: { title: '商品管理' },
                },
                {
                    path: 'products/categories',
                    name: 'AdminProductCategories',
                    component: () => import('@/views/admin/product/CategoryManager.vue'),
                    meta: { title: '分类管理' },
                },
                {
                    path: 'orders',
                    name: 'AdminOrders',
                    component: () => import('@/views/admin/order/OrderListView.vue'),
                    meta: { title: '订单管理' },
                },
                {
                    path: 'orders/:id',
                    name: 'AdminOrderDetail',
                    component: () => import('@/views/admin/order/OrderDetailView.vue'),
                    meta: { title: '订单详情' },
                },
                {
                    path: 'users',
                    name: 'AdminUsers',
                    component: () => import('@/views/admin/user/UserListView.vue'),
                    meta: { title: '用户管理' },
                },
                // Add other admin routes here, e.g., products, orders
            ],
        },

        // --- 404 ---
        {
            path: '/:pathMatch(.*)*',
            name: 'NotFound',
            component: () => import('@/views/NotFoundView.vue'),
            meta: {
                title: '页面不存在',
            },
        },
    ],
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()

    // 设置页面标题
    if (to.meta.title) {
        document.title = `${to.meta.title} - PMall`
    }

    // 后台路由守卫
    if (to.meta.requiresAdmin) {
        if (userStore.isAdmin) {
            next()
        } else {
            next({ path: '/login', query: { redirect: to.fullPath } })
        }
        return
    }

    // --- 前台路由守卫 ---

    // 检查是否需要登录
    if (to.meta.requiresAuth && !userStore.isAuthenticated) {
        next({
            path: '/login',
            query: { redirect: to.fullPath },
        })
        return
    }

    // 检查是否需要游客状态（已登录用户不能访问登录注册页）
    if (to.meta.requiresGuest && userStore.isAuthenticated) {
        next('/')
        return
    }

    next()
})

// 路由错误处理
router.onError((error) => {
    console.error('路由错误:', error)
})

export default router
